<template>
  <div class="content">
    <p class="top_p"><span>1</span> 基本信息 —————————— <span>2</span> 参数配置</p>
    <div>
      <h4>基本信息</h4>
      <a-form id="rejisterOneForm" :model="pinia.$state.peopleOnePageNewData" :rules="rules" name="hhh" :label-col="{ span: 3 }" :wrapper-col="{ span: 20 }" autocomplete="off" @finish="handleNext">
        <a-form-item label="接口分类" name="dirId">
          <a-tree-select
            v-model:value="pinia.$state.peopleOnePageNewData.dirId"
            v-model:searchValue="searchValue"
            show-search
            style="width: 100%"
            :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }"
            placeholder="请选择接口分类"
            allow-clear
            tree-default-expand-all
            :tree-data="treeDatas"
          >
            <template #title="{ value: val, title }">
              {{ title }}
              <!-- <template v-for="(fragment, i) in title.toString().split(new RegExp(`(?<=${searchValue})|(?=${searchValue})`, 'i'))">
                <span v-if="fragment.toLowerCase() === searchValue.toLowerCase()" :key="i" style="color: red">
                  {{ fragment }}
                </span>
                <template v-else>{{ fragment }}</template>
              </template> -->
            </template>
          </a-tree-select>
        </a-form-item>

        <a-form-item label="接口名称" name="portsName">
          <a-input v-model:value="pinia.$state.peopleOnePageNewData.portsName" placeholder="请输入接口名称" />
        </a-form-item>
        <a-form-item label="接口来源" name="portsSource">
          <a-select v-model:value="pinia.$state.peopleOnePageNewData.portsSource" :options="portsSources" placeholder="请选择接口来源"></a-select>
        </a-form-item>
        <a-form-item label="接口描述" name="portsMsg">
          <a-textarea v-model:value="pinia.$state.peopleOnePageNewData.portsMsg" placeholder="请输入接口描述" />
        </a-form-item>
        <h4>API参数</h4>
        <a-form-item label="协议" name="portsProtocol">
          <a-select v-model:value="pinia.$state.peopleOnePageNewData.portsProtocol" :options="portsProtocolOptions" placeholder="请选择协议">
            <!-- <a-select-option value="HTTP">HTTP</a-select-option>
            <a-select-option value="HTTPS">HTTPS</a-select-option> -->
          </a-select>
        </a-form-item>

        <a-form-item label="IP端口" name="portsIp">
          <a-input v-model:value="pinia.$state.peopleOnePageNewData.portsIp" placeholder="请输入IP端口,例如(168.192.0.0:8080)" />
        </a-form-item>
        <a-form-item label="Path" name="portsPath">
          <a-input v-model:value="pinia.$state.peopleOnePageNewData.portsPath" placeholder="请输入Path" />
        </a-form-item>
        <a-form-item label="请求方式" name="portsRequestMethod">
          <a-select v-model:value="pinia.$state.peopleOnePageNewData.portsRequestMethod" :options="portsRequestMethodOptions" placeholder="请选择请求方式">
            <!-- <a-select-option value="POST">POST</a-select-option>
            <a-select-option value="GET">GET</a-select-option> -->
          </a-select>
        </a-form-item>
        <a-form-item label="超时时间" name="portsOutTime">
          <a-input v-model:value="pinia.$state.peopleOnePageNewData.portsOutTime" placeholder="请输入超时时间" /><span class="miao">s</span>
        </a-form-item>
        <footer>
          <a-button type="primary" html-type="submit">下一步</a-button>&nbsp; <a-button type="primary" @click="$router.push('/home/Interfaceto')">取消</a-button> &nbsp;
          <a-button type="primary" @click="handleSaveAndQuit">保存并退出</a-button>
        </footer>
      </a-form>
    </div>
  </div>
</template>
<script setup lang="ts">
  import { reactive, ref } from 'vue';
  import type { Ref, UnwrapRef } from 'vue';
  import type { Rule } from 'ant-design-vue/es/form';
  import { message } from 'ant-design-vue';
  import { Registration1, interFace, getinterFace } from '@/api/test/interFace';
  import { useStore } from './pinia/pinia';
  import type { TreeSelectProps } from 'ant-design-vue';
  import router from '@/router';
  import { OnePageType } from '../type';
  interface FormState {
    dirId: number | string; //接口分类
    portsName: string; //接口名称
    portsSource: string; // 接口来源
    portsMsg: string; // 接口描述
    portsProtocol: number | string; // 协议
    portsIp: string; // IP端口
    portsPath: string; // 路径
    portsRequestMethod: number | string; // 请求方式
    portsOutTime: number; // 超时时间
    portsStatus?: number;
    addTime?: string;
    modifyTime?: string;
  }
  const props = defineProps({
    datalistOnePage: {
      type: Object,
      default: () => {
        return {};
      },
    },
  });
  // 接口协议下拉框选项
  const portsProtocolOptions = [
    {
      label: 'HTTP',
      value: 1,
    },
    {
      label: 'HTTPS',
      value: 2,
    },
  ];
  // 请求方式下拉框选项
  const portsRequestMethodOptions = [
    {
      label: 'GET',
      value: 1,
    },
    {
      label: 'POST',
      value: 2,
    },
  ];
  // 搜索框
  let searchValue = ref('');
  let portsSources = ref([]);
  const treeDatas = ref<TreeSelectProps['treeData']>([]);
  const handleTreeDatas = (data: { dirName: any; dirId: any; children?: any }[]) => {
    let datas: any = [];
    datas = data.map((item: { dirName: any; dirId: any; children?: any }) => {
      return {
        title: item.dirName,
        value: item.dirId,
        children: item.children.length > 0 ? handleTreeDatas(item.children) : '',
      };
    });
    return datas;
  };
  onMounted(async () => {
    // 接口来源
    const resinterFace = await interFace();
    portsSources.value = resinterFace.data.map(item => {
      return { label: item.portsSource, value: resinterFace.data.indexOf(item) };
    });
    // 接口分类
    const resgetinterFace = await getinterFace();
    treeDatas.value = handleTreeDatas(resgetinterFace.data);
    console.log(handleTreeDatas(resgetinterFace.data), 'dadafafaf');
    console.log(treeDatas.value, '2232ada');

    // // 编辑接口
    // let portsId;
    // if (route.query.portsId) {
    //   // portsId = route.query.portsId;
    //   portsId = parseInt(route.query.portsId);
    // }
    // console.log(portsId, 'dadada');

    // let res = await selectDir({ portsId });
    // datalistOnePage.value = res.data.ports;
    // console.log('dd', res.data.ports);
    // // 发请求
  });
  const pinia = useStore();

  pinia.getPeopleOnePageNewData();

  watch(
    () => props.datalistOnePage as OnePageType,
    (nval: OnePageType) => {
      // formState = nval;
      console.log(nval, '2e2323232323');
      // const data = {nval.portsName};
      pinia.getPeopleOnePageNewData(nval);
    },
  );
  const emit = defineEmits(['nextPage']);
  // console.log(formState);
  const timeValidator = (_rule: any, value: number, callback: any) => {
    if (value >= 0 && value <= 1800) {
      return callback();
    } else {
      return new Promise((resolve, reject) => {
        reject('超时时间限制在0-1800s');
      });
    }
  };
  const rules: Record<string, Rule[]> = {
    dirId: [
      { required: true, message: '接口分类不能为空', trigger: ['blur', 'change'] },
      { pattern: /^[\u4e00-\u9fa5_a-zA-Z0-9]+$/, message: '码表名称必须为汉字或字母组成', trigger: ['blur', 'change'] },
      // { validator: NameValidator, trigger: ['blur', 'change'] },
    ],
    portsRequestMethod: [{ required: true, message: '请求方式不能为空', trigger: ['blur', 'change'] }],
    portsName: [
      { required: true, message: '接口名称不能为空' },
      { max: 30, message: '名称最长不能超过30个字符' },
      { pattern: /^\S*$/, message: '不能包含空格', trigger: ['blur', 'change'] },
    ],
    portsProtocol: [
      { required: true, message: '协议不能为空', trigger: ['blur', 'change'] },
      { pattern: /^[\u4e00-\u9fa5_a-zA-Z0-9]+$/, message: '码表名称必须为汉字或字母组成', trigger: ['blur', 'change'] },
      // { validator: NameValidator, trigger: ['blur', 'change'] },
    ],
    portsIp: [
      { required: true, message: 'IP端口不能为空', trigger: ['blur', 'change'] },
      {
        message: '请输入正确格式的IP!',
        trigger: 'blur',
        pattern:
          /^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])(\:([0-9]|[1-9]\d{1,3}|[1-5]\d{4}|6[0-5]{2}[0-3][0-5])){0,1}$/,
      },
    ],
    portsPath: [{ required: true, message: '接口路径不能为空', trigger: ['blur', 'change'] }],
    portsSource: [{ required: true, message: '接口来源不能为空', trigger: ['blur', 'change'] }],
    portsOutTime: [
      { required: true, message: '超时时间不能为空' },
      { validator: timeValidator, trigger: ['blur', 'change'] },
    ],
  };
  //   下一步按钮
  let handleNext = async () => {
    emit('nextPage', { num: 2 });
  };
  const handleSaveAndQuit = async () => {
    // 发请求新增
    // pinia.$state.peopleOnePageNewData.dirId = pinia.$state.peopleOnePageNewData.dirId.split('-')[0];
    const res = await Registration1(pinia.$state.peopleOnePageNewData);
    console.log(res, '我试试十四');
    pinia.getPeopleOnePageNewData();
    // router.push('/home/Interfaceto');
  };
  // 随机生成数字
  // let cg = () => {
  //   return Math.random() * 999;
  // };
  // 检查名字是否重复
  // const NameValidator = (_rule: any, value: string, callback: any) => {
  //   if (value) {
  //     console.log(value);
  //     let nameLength: number = props.newData?.split(',').indexOf(value);
  //     console.log(nameLength, 'nametheght');
  //     if (nameLength == -1) {
  //       return Promise.resolve();
  //     } else {
  //       return new Promise((resolve, reject) => {
  //         reject('码表名称不能重复');
  //       });
  //     }
  //   } else {
  //     return Promise.resolve();
  //   }
  // };
  // 检查是否为汉字
  // const isHan = () => {
  //   let han = /^[\u4e00-\u9fa5]{2,16}$/;
  //   //获取输入框中的数据
  //   let vals = formState.value.portsName;
  //   if (!han.test(vals)) {
  //     return false;
  //   } else {
  //     return true;
  //   }
  // };
  // 底部按钮---------------
  // 取消按钮
  let cacelbottombtn: Ref<boolean> = ref(false);
</script>
<style lang="less" scoped>
  .content {
    width: 100%;

    div {
      h4 {
        margin-left: 50px;
        font-weight: 600;
      }
    }

    .top_p {
      margin-top: 10px;
      border-bottom: 1px solid rgb(179, 179, 179);
      width: 100%;
      height: 40px;
      text-align: center;

      span {
        display: inline-block;
        border-radius: 50%;
        width: 30px;
        height: 30px;
        line-height: 30px;
      }

      span:nth-child(1) {
        color: aliceblue;
        background-color: #4da0ff;
      }

      span:nth-child(2) {
        border: #000 1px solid;
        color: #000;
      }
    }
  }

  :deep(.miao) {
    position: relative;
    bottom: 28px;
    left: 100.2%;
  }

  :deep(.ant-table-thead > tr > th:not(.ant-table-cell:nth-child(3)):not(.ant-table-selection-column):not(.ant-table-row-expand-icon-cell):not([colspan])::before) {
    position: static;
    transform: translateY(0px);
  }

  :deep(.ant-table-thead > tr > th:not(.ant-table-cell:nth-child(3)):not(:last-child):not(.ant-table-selection-column):not(.ant-table-row-expand-icon-cell):not([colspan])::before) {
    display: inline-block;
    margin-right: 8px;
    font-size: 14px;
    font-family: SimSun, sans-serif;
    color: #ff4d4f;
    content: '*';
  }

  footer {
    width: 100%;
    height: 50px;
    line-height: 50px;
    text-align: center;
  }
</style>
